import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {Button, Card, Col, Divider, Form, Icon, Input, Modal, Row, Table} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../PrivateFile.less';
import MoveFileForm from '../sub/MoveFileForm';
import DirLine from "../sub/DirLine";
import {getReadableSize,hasInstalledEditApp} from '@/utils/dsrsUtil';
import CopyFileForm from "../sub/CopyFileForm";
import UploadFileForm from '../sub/UploadFileForm';
import wordIcon from '@/iconImg/word.png';
import excelIcon from '@/iconImg/excel.png';
import pptIcon from '@/iconImg/ppt.png';
import pdfIcon from '@/iconImg/pdf.png';
import zipIcon from '@/iconImg/zip.png';
import txtIcon from '@/iconImg/txt.png';
import picIcon from '@/iconImg/pic.png';
import csvIcon from '@/iconImg/csv.png';
import otherIcon from '@/iconImg/other.png';
import batIcon from '@/iconImg/bat.png';
import sqlIcon from '@/iconImg/sql.png';
import shIcon from '@/iconImg/sh.png';
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({outFileModel, loading}) => ({
  outFileModel,
  loading: loading.models.outFileModel,
}))
@Form.create()
class OutFiles extends PureComponent {
  state = {
    isQueryIng: false,
    copyModalVisible: false,
    moveModalVisible: false,
    uploadModalVisible: false,
    supportUploadFileTypes: "",
    fileMaxUploadSize: "500",
    selectedRows: [],
    record: {},
    currentDirs: [
      {code: 'ftp_list', dirName: '外接文件', ftpId: "", parentPath: ""},
      {code: 'ftp_id', dirName: 'xxx组', ftpId: this.props.match.params.ftpId, parentPath: "/"},
    ],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'dirName',
      render: (text, row) => {
        if (row.dirType == 1) {
          return <Fragment>
            <Icon type="folder" theme="filled" style={{color: '#e87e04'}}/>&nbsp;
            <a onClick={() => this.querySubDir(row)}>{text}</a>
          </Fragment>
        } else {
          let fielIcon = '';
          switch ('.' + row.dirName.split('.')[1]) {
            case '.wps':
              case '.doc':
              case '.docx':
                fielIcon = wordIcon;             
                break;
              case '.txt':
                  fielIcon = txtIcon;
                  break;  
              case '.bat':             
                fielIcon = batIcon;
                break; 
              case '.sh':             
                fielIcon = shIcon;
                break;   
              case '.sql':             
                fielIcon = sqlIcon;
                break;     
              case '.ppt':
              case '.pptx':
                fielIcon = pptIcon;             
                break;          
              case '.xls':
              case '.xlsx':
                fielIcon = excelIcon; 
                break;   
              case '.pdf':
                fielIcon = pdfIcon; 
                break;
              case '.zip':
              case '.gz':
              case '.tar':
              case '.rar':
                fielIcon = zipIcon;              
                break;     
              case '.jpg':
              case '.png':
              case '.gif':
                fielIcon = picIcon;              
                break;  
              case '.csv':
                fielIcon = csvIcon;              
                  break;              
              default:
                fielIcon = otherIcon;
          }

          return <Fragment>
             <img src={fielIcon} />&nbsp;
            {text}
          </Fragment>
        }
        return null;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',

      render:
        val => val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : null,
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      render: (text, record) => {
        if (text) {
          return getReadableSize(text * 1024);
        } else {
          return '--'
        }
      },
    },
    {
      title: '操作',
      render:
        (text, record) => {
          const {
            outFileModel: {data,},
          } = this.props;
          const deleteRecord = <a onClick={() => this.deleteData(record)}>删除</a>;
          const copyToUpload = <a onClick={() => this.copyToUpload(record)}>复制到上传</a>;
          const moveToUpload = <a onClick={() => this.moveToUpload(record)}>移动到上传</a>;


          if (record.dirType == 0) {
            return <Fragment>
              <a onClick={() => this.previewItem(record)}>预览</a>
              <Divider type="vertical"/>
              <a onClick={() => this.handleCopyModalVisible(true, record)}>复制</a>
              <Divider type="vertical"/>
              <a onClick={() => this.handleMoveModalVisible(true, record)}>移动</a>

              {data.canUpload ? <Divider type="vertical"/> : null}
              {data.canUpload ? deleteRecord : null}

              {data.canMoveOrCopy ? <Divider type="vertical"/> : null}
              {data.canMoveOrCopy ? copyToUpload : null}

              {data.canMoveOrCopy ? <Divider type="vertical"/> : null}
              {data.canMoveOrCopy ? moveToUpload : null}
            </Fragment>
          }
        },
    },
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    this.backToRoot();
    dispatch({
      type: 'outFileModel/queryDirTreeList',
      payload: null,
    });   
  }



  deleteData = (record) => {
    Modal.confirm({
      title: '删除',
      content: '一旦删除将无法恢复，确定删除？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(record),
    });
  };
  copyToUpload = (record) => {
    Modal.confirm({
      title: '复制',
      content: '复制的文件将同步到其他堡垒机',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.copyFileToUpload(record),
    });
  };
  moveToUpload = (record) => {
    Modal.confirm({
      title: '移动',
      content: '移动的文件将同步到其他堡垒机',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.moveFileToUpload(record),
    });
  };

  deleteItem = record => {
    const {dispatch} = this.props;
    dispatch({
      type: 'outFileModel/deleteOutSideFileOrDir',
      payload: {
        ftpId: record.ftpId,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.refreshList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }

      },
    });

  };
  copyFileToUpload = record => {
    const {dispatch} = this.props;
    dispatch({
      type: 'outFileModel/copyFileToUpload',
      payload: {
        ftpId: record.ftpId,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.refreshList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }

      },
    });

  };
  moveFileToUpload = record => {
    const {dispatch} = this.props;
    dispatch({
      type: 'outFileModel/moveFileToUpload',
      payload: {
        ftpId: record.ftpId,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          // this.refreshList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });

  };

  backToRoot() {
    const {dispatch} = this.props;
    const ftpId = this.props.match.params.ftpId;
    const ftpName = this.props.match.params.ftpName;
    let queryForm = {};
    queryForm.ftpId = ftpId;
    queryForm.path = '/';
    dispatch({
      type: 'outFileModel/queryList',
      payload: queryForm,
    });

    this.setState({
      currentDirs: [
        {code: 'index', dirName: '我的文件库', ftpId: "", parentPath: ""},
        {code: 'ftp_list', dirName: '外接文件', ftpId: "", parentPath: ""},
        {code: 'ftp_id', dirName: ftpName, ftpId: this.props.match.params.ftpId, parentPath: "/"},
      ],
    });
  }

  //重新获取文件列表
  refreshList() {
    //更改当前的显示
    let currentDirs = this.state.currentDirs;
    // 选取最后一个id/
    const row = currentDirs[currentDirs.length - 1];
    // this.onDirSelect(lastItem);
    // this.querySubDir(lastItem);
    const {dispatch} = this.props;
    let queryForm = {};
    queryForm.ftpId = row.ftpId;
    if (row.parentPath && row.parentPath.length > 1) {
      queryForm.path = row.parentPath + "/" + row.dirName;
    } else if (row.parentPath == "/") {
      queryForm.path = "/";
    } else {
      return;
    }
    dispatch({
      type: 'outFileModel/queryList',
      payload: queryForm,     
    });
  }

  //选中了目录
  onDirSelect = item => {
    const isQueryIng = this.state.isQueryIng;
    if (isQueryIng) {
      return;
    }
    switch (item.code) {
      case 'index':
        router.push('/filecenter/home-file');
        break;
      case 'ftp_list':
        router.push('/filecenter/out-file');
        break;
      case 'ftp_id':
        this.backToRoot();
        break;
      case 'sub_file':
        //更改当前的显示
        let currentDirs = this.state.currentDirs;
        let newDirs = [];
        let currentRow = {};
        for (let temp of currentDirs) {
          if (item.id == temp.id) {
            currentRow = temp;
            break;
          }
          newDirs.push(temp);
        }
        this.setState({currentDirs: newDirs});
        //查询文件夹下的子文件
        this.querySubDir(currentRow);
        break;
        default:
        break;
    }

  }


  //显示文件夹下级内容
  querySubDir = (row) => {
    const {dispatch} = this.props;
    let queryForm = {};
    queryForm.ftpId = row.ftpId;

    if (row.parentPath && row.parentPath.length > 1) {
      queryForm.path = row.parentPath + "/" + row.dirName;
    } else if (row.parentPath == "/") {
      queryForm.path = "/" + row.dirName;
    } else {
      return;
    }

    this.setState({
      isQueryIng: true,
    });

    dispatch({
      type: 'outFileModel/queryList',
      payload: queryForm,
      callback: (res) => {
        this.setState({
          isQueryIng: false,
        });

        if (res.result == "ok") {
          this.addRowToCurrent({
            id: queryForm.path,
            ftpId: row.ftpId,
            dirName: row.dirName,
            parentPath: row.parentPath,
          });
        }
      },
    });
  };

  addRowToCurrent = (item) => {
    this.state.currentDirs.push(item);
  }


  /***预览文件**/
  previewItem = record => {
    const {dispatch,} = this.props;
    if (!hasInstalledEditApp()) {
      //如果没有安装客户端，下载在线编辑客户端
      Modal.warning({title: '请先下载安装在线编辑客户端'});
      this.downloadBwdaOnlineEdit();
      return;
    }
    dispatch({
      type: 'outFileModel/getPreviewLinkPath',
      payload: {
        ftpId: record.ftpId,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {

          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };  

  downloadBwdaOnlineEdit = () => {
    window.open("/DSRS-OnlineEdit.exe", "_self");
  }

  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
        parentId: 0,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'outFileModel/queryList',
        payload: values,

      });
    });
  };
  /********移动文件到其他地方*******/
  handleMove = (newParentId, record) => {
    const {dispatch,} = this.props;
    dispatch({
      type: 'outFileModel/moveFile',
      payload: {
        ftpId: record.ftpId,
        parentId: newParentId || 0,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        if (res.result == "ok") {
          this.queryUserfilespace()
          Modal.success({title: res.msg});
          // this.refreshList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleMoveModalVisible();
  };

  /********复制文件到其他地方*******/
  handleCopy = (newParentId, record) => {
    const {dispatch,} = this.props;
    dispatch({
      type: 'outFileModel/copyFile',
      payload: {
        ftpId: record.ftpId,
        parentId: newParentId || 0,
        path: record.parentPath + "/" + record.dirName,
      },
      callback: (res) => {
        this.handleCopyModalVisible();
        if (res.result == "ok") {
          this.queryUserfilespace()
          Modal.success({title: res.msg});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });

  };


  // 进度条--使用空间
  queryUserfilespace = () => {
    const {dispatch} = this.props;
    dispatch({
      type: 'user/queryUFS',
    });
  }
  /**
   * 移动文件弹出框
   * @param flag
   * @param record
   */
  handleMoveModalVisible = (flag, record) => {
    this.setState({
      moveModalVisible: !!flag,
      record: record || {},
    });
  };
  /**
   * 复制文件弹出框
   * @param flag
   * @param record
   */
  handleCopyModalVisible = (flag, record) => {
    this.setState({
      copyModalVisible: !!flag,
      record: record || {},
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('dirName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="创建人">
              {getFieldDecorator('creater')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleUploadModalVisible = flag => {
    this.setState({
      uploadModalVisible: !!flag,
    });
  };

  /*****上传成功*****/
  handleUpload = () => {
    const {currentDir} = this.state;
    this.handleUploadModalVisible();
    this.refreshList();
  };


  render() {

    const {
      outFileModel: {data, dirTreeList,},
      loading,
    } = this.props;
    const {copyModalVisible, moveModalVisible, record, currentDirs, uploadModalVisible, supportUploadFileTypes, fileMaxUploadSize,} = this.state;
    const ftpId = this.props.match.params.ftpId;
    //移动文件
    const moveMethods = {
      handleMove: this.handleMove,
      handleModalVisible: this.handleMoveModalVisible,
    };
    //移动文件
    const copyMethods = {
      handleCopy: this.handleCopy,
      handleModalVisible: this.handleCopyModalVisible,
    };
//上传文件
    const uploadMethods = {
      handleUpload: this.handleUpload,
      handleModalVisible: this.handleUploadModalVisible,
    };


    return (
      <PageHeaderWrapper title="外接文件">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.filePath}>
              <DirLine dirs={currentDirs} onDirSelect={this.onDirSelect}/>
              {data.canUpload ?
                <Button icon="upload" type="primary" onClick={() => this.handleUploadModalVisible(true)} style={{marginRight:10}}>
                  上传
                </Button> : null}
                <Button type="primary" onClick={() => this.refreshList()}>
                  刷新
                </Button>
            </div>
            <Table
            loading={loading} 
            className={styles.tdPadding} 
            columns={this.columns} 
            dataSource={data.dataList}           
            />

          </div>
        </Card>
        <MoveFileForm loading={loading} {...moveMethods} modalVisible={moveModalVisible} record={record}
                      dirTreeList={dirTreeList}/>
        <CopyFileForm loading={loading} {...copyMethods} modalVisible={copyModalVisible} record={record}
                      dirTreeList={dirTreeList}/>
        {uploadModalVisible ?
          <UploadFileForm {...uploadMethods} modalVisible={uploadModalVisible} currentDir={{}}
                          uploadUrl={"privateFileModel/uploadOutsideFiles"}
                          supportUploadFileTypes={supportUploadFileTypes}
                          ftpId={ftpId}
                          fileMaxUploadSize={fileMaxUploadSize}/> : null}
      </PageHeaderWrapper>
    );
  }
}

export default OutFiles;
